<?php

namespace app\common\model\mycurrency;

use app\common\library\MerchantStaffAuth;
use app\common\library\MerchantStaffToken;
use app\common\model\mycurrency\MerchantStaff as User;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;
use think\Model;

/**
 * 工作人员模型
 */
class MerchantStaff extends Model
{
    // 表名
    protected $name = 'mycurrency_merchant_staff';

    const IDENTITY_DAILI = 1;//身份:1=代理
    const IDENTITY_YEWU = 2;//身份:2=业务员
    const IDENTITY_MENDIAN = 3;//身份:3=门店

    /**
     * 注册用户
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param array  $extend   扩展参数
     * @return boolean
     */
    public static function register($username, $password, $email = '', $mobile = '', $extend = [])
    {
        // 检测用户名、昵称、邮箱、手机号是否存在
        if (User::getByUsername($username)) {
            throw new Exception('用户名已存在');
            return false;
        }
        if (User::getByNickname($username)) {
            throw new Exception('昵称已存在');
            return false;
        }
        if ($email && User::getByEmail($email)) {
            throw new Exception('邮箱已存在');
            return false;
        }
        if ($mobile && User::getByMobile($mobile)) {
            throw new Exception('手机号已存在');
            return false;
        }
        $ip = request()->ip();
        $time = time();
        $data = [
            'username' => $username,
            'password' => $password,
            'email'    => $email,
            'mobile'   => $mobile,
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];
        $params = array_merge($data, [
            'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $merchant_staff_auth = new MerchantStaffAuth();
        $params['password'] = $merchant_staff_auth->getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);
        $res = self::create($params,true);

        return true;
    }
}
